#!/usr/bin/env python
#coding=utf-8
import json
import time
import logging
import traceback
from datetime import datetime
from random import shuffle
from flask_cache import Cache
from flask import render_template, url_for, redirect, request, flash, session, abort, Blueprint
from werkzeug.contrib.atom import AtomFeed
from models.model import Category, Post, Tag, Comment, pageby, db
from config import PER_PAGE as per_page
# from pitaya import app

tags = Blueprint('tags', __name__, url_prefix="/tags")

log = logging.getLogger(__file__)

# cache = Cache(app, config={'CACHE_TYPE': 'simple'})

# app.jinja_env.filters['html2textile'] = html2textile


@tags.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@tags.route('/error/404')
def error_404():
    return render_template('404.html'), 404


@tags.route('/tag/<int:tagid>')
@tags.route('/tag/<int:tagid>/page/<int:pageid>')
# @cache.cached(timeout=300)
def tag_detail(tagid=1, pageid=1):
    categorys = Category.query.getall()
    hot = Post.query.hottest()[:20]
    new = Post.query.newpost()[:20]
    tag = Tag.query.getall()
    shuffle(tag)
    tag = tag[:20]
    comments = Comment.query.newcomment()[:20]

    tagall = Tag.query.get_or_404(tagid)
    name = tagall.name
    p = Post.query.search_tag(name)
    p = pageby(p, pageid, per_page, Post.post_create_time.desc())

    articles = p.items
    if not p.total:
        pagination = [0]
    elif p.total % per_page:
        pagination = range(1, p.total / per_page + 2)
    else:
        pagination = range(1, p.total / per_page + 1)

    return render_template('/tag.html',
                           id=tagid,
                           tagall=tagall,
                           categorys=categorys,
                           articles=articles,
                           hotarticles=hot,
                           newpost=new,
                           tags=tag,
                           comments=comments,
                           pageid=pageid,
                           pagination=pagination[pageid - 1:pageid + 10],
                           last_page=pagination[-1]
                           )


@tags.route('/search')
@tags.route('/search/page/<int:pageid>')
# @cache.cached(timeout=240)
def search(pageid=1):
    categorys = Category.query.getall()
    hot = Post.query.hottest()[:20]
    new = Post.query.newpost()[:20]
    tag = Tag.query.getall()
    shuffle(tag)
    tag = tag[:20]
    comments = Comment.query.newcomment()[:20]

    searchword = request.args.get('s', '')
    if not searchword:
        return redirect(url_for('error_404'))

    searchresult = Post.query.search(searchword)

    p = pageby(searchresult, pageid, per_page, Post.post_create_time.desc())

    articles = p.items
    if not p.total:
        pagination = [0]
    elif p.total % per_page:
        pagination = range(1, p.total / per_page + 2)
    else:
        pagination = range(1, p.total / per_page + 1)

    return render_template('/search.html',
                           key=searchword,
                           categorys=categorys,
                           articles=articles,
                           hotarticles=hot,
                           newpost=new,
                           tags=tag,
                           comments=comments,
                           pageid=pageid,
                           pagination=pagination[pageid - 1:pageid + 10],
                           last_page=pagination[-1]
                           )

@tags.route('/error')
def error(content='404'):
    return render_template('/error.html', content=content)



